
package models.security;

import java.util.List;

import javax.persistence.Entity;
import javax.persistence.TypedQuery;

import models.Store;
import models.aaa.Node;

import org.apache.commons.lang.StringUtils;

import play.db.jpa.JPA;

/**
 * @author laurent@opprecht.info
 */
@Entity
public class Role extends Node {// implements be.objectify.deadbolt.models.Role

                                // {

    public static class Finder {

        public TypedQuery<Role> createQuery(final String sql) {
            TypedQuery<Role> result = JPA.em().createQuery(sql, Role.class);
            return result;
        }

        public TypedQuery<Role> query(final String sql, final Object... parameters) {
            TypedQuery<Role> result = createQuery(sql);
            for (int i = 0; i < parameters.length; i++) {
                result.setParameter(i + 1, parameters[i]);
            }
            return result;
        }

        public Role byId(final Long id) {
            return JPA.em().find(Role.class, id);
        }

        public Role byName(final String name) {
            if (StringUtils.isEmpty(name)) {
                return null;
            }

            TypedQuery<Role> query = query("SELECT e FROM Role e WHERE e.name = ?", name);
            List<Role> items = query.getResultList();
            for (Role item : items) {
                return item;
            }
            return null;
        }
    }

    public static Finder find = new Finder();

    public static Role get(final String name) {
        if (name == null) {
            return null;
        }
        Role result = find.byName(name); //
        if (result != null) {
            return result;
        }
        result = new Role(name);
        Store.save(result);
        return result;
    }

    public String name;

    public Role() {

    }

    public Role(final String name) {
        this.name = name;
    }

    // @Override
    public String getRoleName() {
        return name;
    }

    @Override
    public String toString() {
        return name;
    }

}